package com.sirui.spider.processor;

import com.sirui.spider.downloader.SeleniumDownloader;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * 花瓣网抽取器。<br>
 * 使用Selenium做页面动态渲染。<br>
 */
public class HuabanProcessor implements PageProcessor {

    private Site site;

    public static void main(String[] args) {
        Spider.create(new HuabanProcessor()).thread(5)
                .addPipeline(new FilePipeline("d:\\logs\\webmagic\\"))
                .setDownloader(new SeleniumDownloader("D:\\tools\\webdriver\\chromedriver_win32\\chromedriver.exe"))
                .addUrl("http://huaban.com/")
                .runAsync();
    }

    @Override
    public void process(Page page) {
        // 加入其它页面
        List<String> urlList = page.getHtml().links().regex("http://huaban\\.com/.*").all();
        page.addTargetRequests(urlList);
        // 保存信息
        if (page.getUrl().toString().contains("pins")) {
            page.putField("img", page.getHtml().xpath("//div[@class='image-holder']/a/img/@src").toString());
        } else {
            page.getResultItems().setSkip(true);
        }
    }

    @Override
    public Site getSite() {
        if (null == site) {
            site = Site.me().setDomain("huaban.com").setSleepTime(0);
        }
        return site;
    }
}